<?php
declare(strict_types=1);

namespace app\controller\api\admin;

use think\Request;
use think\exception\ValidateException;
use app\controller\api\ApiBaseController;
use think\facade\Session;
use app\validate\api\admin\LoginValidate;
use app\logic\api\admin\LoginLogic;


class LoginController extends ApiBaseController
{
    public function login(Request $request)
    {
        $data = $request->only([
            'username',
            'password',
            'captcha' => 'placeholder',
            'captcha_token' => '',
        ]);

        // 不让其为空 影响reqiure验证 LOGIN_CAPTCHA_CHECK=1时的无缓存第一次
        if ($data['captcha'] == '') {
            $data['captcha'] = 'placeholder';
        }

        try {
            $validate = validate(LoginValidate::class);

            if ($data['captcha_token'] == '') {
                $data['captcha_token'] = Session::getId();
            } else {
                $validate->scene('loginBefore')->check($data);
                Session::setId($data['captcha_token']);
                Session::init();
            }

            $validate->scene('login')->check($data);

            $logic = new LoginLogic();
            $lgc_re = $logic->login($data);

            return $lgc_re['code'] == 200
                ? $this->success($lgc_re['msg'], $lgc_re['data'])
                : $this->error($lgc_re['msg']);
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        }
    }

    public function refreshToken(Request $request)
    {
        $data = $request->only([
            'refresh_token' => '',
        ]);

        try {
            $validate = validate(LoginValidate::class);
            $validate->scene('refreshToken')->check($data);

            // 补充 验证后 额外参数
            $data['old_jwt_data'] = $validate->getExData('old_jwt_data');

            $logic = new LoginLogic();
            $lgc_re = $logic->refreshToken($data);

            return $lgc_re['code'] == 200
                ? $this->success($lgc_re['msg'], $lgc_re['data'])
                : $this->error($lgc_re['msg']);
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        }
    }

    public function getRoutes(Request $request)
    {
        $data = [
            'user_id' => $request->x_token_user['id'] ?? 0,
        ];
        $logic = new LoginLogic();
        $lgc_re = $logic->getRoutes($data);

        return $lgc_re['code'] == 200
            ? $this->success($lgc_re['msg'], $lgc_re['data'])
            : $this->error($lgc_re['msg']);
    }
}
